/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package ca.inrs.ete.app.shopx.sync;


import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.Intent;
import android.content.SyncResult;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import ca.inrs.ete.app.shopx.util.Constants;

/**
 * SyncAdapter implementation for syncing sample SyncAdapter contacts to the
 * platform ContactOperations provider.  This sample shows a basic 2-way
 * sync between the client and a sample server.  It also contains an
 * example of how to update the contacts' status messages, which
 * would be useful for a messaging or social networking client.
 */
public class SyncAdapter extends AbstractThreadedSyncAdapter {

	private static final String TAG = "SHOPLog.SyncAdapter";

	private static final boolean NOTIFY_AUTH_FAILURE = true;

	private final AccountManager mAccountManager;
	private final Context 		 mContext;

	public SyncAdapter(Context context, boolean autoInitialize) {
		super(context, autoInitialize);
		mContext = context;
		mAccountManager = AccountManager.get(context);
	}

	@Override
	public void onPerformSync(Account account, 
			Bundle extras, 
			String authority,
			ContentProviderClient provider, 
			SyncResult syncResult)
	{

		try {
			Log.d(TAG, "Sync files");

			// Get the last data directory synchronized
			String lastSyncMarker = getServerUserData(account, Constants.ACCOUNT_KEY_MARKER);

			// Use the account manager to request the AuthToken.  If we don't
			// have an AuthToken yet, this could involve a round-trip to the
			// server to request and AuthToken.
			mAccountManager.blockingGetAuthToken(account, Constants.AUTHEN_TOKEN_TYPE, NOTIFY_AUTH_FAILURE);

			// Get synchronization data
			String usr = account.name;
			String pwd = mAccountManager.getPassword(account);
			String uri = getServerUserData(account, Constants.ACCOUNT_KEY_URI);
			String lng = getServerUserData(account, Constants.ACCOUNT_KEY_LANGUAGE);
			boolean wfi = (getServerUserData(account, Constants.ACCOUNT_KEY_WIFIONLY) == "0") ? false : true;

			// Check wifi network status
			if (wfi && ! Build.FINGERPRINT.contains("generic")) {
				final ConnectivityManager connMgr = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
			    final NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			    if ( networkInfo != null && networkInfo.isConnected() ) {
			        if ( networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
						Log.i(TAG, "Wifi is on");
			        } else if(networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
						Log.i(TAG, "Ethernet is on");
			        } else if(networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
						Intent i = new Intent(Constants.MSG_SYNC_WIFIOFF);
						mContext.sendBroadcast(i);
						Log.i(TAG, "Wifi is off");
						return;
			        }
			    }
			}

			// Synchronize
			String ret = new SyncDownloader().run(mContext, uri, usr, pwd, lng);

			// Save the new directory
			if (ret != null && ret != lastSyncMarker)
				setServerUserData(account, Constants.ACCOUNT_KEY_MARKER, ret);

			if (ret == null) {
				syncResult.stats.numParseExceptions++;
			}

			Intent i = new Intent(Constants.MSG_SYNC_TERMINATED);
			i.putExtra(Constants.MSG_SYNC_KEY_SUCCESS, ret != null);
			mContext.sendBroadcast(i);
		}
		catch (Exception e)
		{
			Log.e(TAG, "AuthenticatorException", e);
			syncResult.stats.numParseExceptions++;
		}
	}

	private String getServerUserData(Account account, String key) {
		String val = mAccountManager.getUserData(account, key);
		if (!TextUtils.isEmpty(val)) {
			return val;
		}
		return null;
	}

	private void setServerUserData(Account account, String key, String val) {
		mAccountManager.setUserData(account, key, val);
	}

}

